﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using WarehouseManagement.BusinessLogic.BC;
using WarehouseManagement.BusinessLogic.DTO;
using WarehouseManagement.DataAccess;

using WarehouseManagement.Shared;

using WarehouseManagement.ViewModels.Import;
using WarehouseManagement.ViewModels.Merchandise;
using WarehouseManagement.Views.Shared;

namespace WarehouseManagement.Presenters.Import
{
    public class NewImportPresenter : BasePresenter<INewImportViewModel>
    {
        private MerchandiseBC _merchandiseBC;
        private CurrencyBC _currencyBC;
        private StockBC _stockBC;
        private ImportBC _ieBC;
        private SupplierBC _supBC;

        private BindingList<ImportDetailDTO> _importDetails;


        public delegate void ImportSaved(bool success);
        public ImportSaved OnImportSaved;

        public NewImportPresenter()
        {
            _merchandiseBC = new MerchandiseBC();
            _currencyBC = new CurrencyBC();
            _ieBC = new ImportBC();
            _stockBC = new StockBC();
            _supBC = new SupplierBC();
            //_importDetails = new BindingList<ImportDetailViewItem>();
            _importDetails = new BindingList<ImportDetailDTO>();
        }

        protected override void WireupEventHandles()
        {

        }

        public void InitializeView()
        {
            LoadSupplierList();
            LoadMerchandiseLookupData();
            if (Model.CurrentEditMode == Views.Export.NewEditImport.EditMode.New)
                Model.ImportDate = DateTime.Now;
            Model.ImportDetailList = _importDetails as BindingList<ImportDetailDTO>;
            if (Model.CurrentEditMode == Views.Export.NewEditImport.EditMode.New)
                LoadCurrencyLookupData();
        }

        public void LoadMerchandiseLookupData()
        {
            var list = _merchandiseBC.GetMerchandiseList();

            Model.MerchandiseList = list.Select(e => new
            {
                MerchandiseUnit = e.Unit,
                MerchandiseId = e.Id,
                e.MerchandiseName,
                QuantityInStock = _stockBC.GetViewStockInfo(e.Id, DateTime.Today, DateTime.Today).EndPeriodQuantity
            }).ToList();
        }

        public void LoadCurrencyLookupData()
        {
            var list = _currencyBC.GetCurrencyList();           
            Model.CurrencyList = list.ToList();
        }

        public void DeleteSelectedItem()
        {
            RemoveImportDetailItem(Model.SelectedImportItem);
        }

        private void RemoveImportDetailItem(Guid detailId)
        {
            var selectedItemId = detailId;

            if (selectedItemId != Guid.Empty)
            {
                var item = _importDetails.SingleOrDefault(e => e.Id == selectedItemId);
                _importDetails.Remove(item);
            }
        }

        public void CreateNewImportNumber()
        {
            _ieBC.RecycleContext();

            //var importItem = _ieBC.GetImportByNumber(Model.ImportNumber);
            //if (importItem == null)
            Model.ImportId = Guid.NewGuid();
            //else
            //    Model.ImportId = importItem.Id;

            Model.ImportNumber = _ieBC.GenerateNewImportNumber();
            Model.ImportDate = DateTime.Now;
            _importDetails = new BindingList<ImportDetailDTO>();
            _importDetails.Clear();
            Model.ImportDetailList = _importDetails;
            Model.Notes = Model.ImportReason = string.Empty;
            Model.CurrentEditMode = Views.Export.NewEditImport.EditMode.New;
        }

        public void SaveImport()
        {
            if (Model.SupplierId == -1)
            {
                XtraMessageBox.Show("Bạn chưa chọn nhà cung cấp", "Chọn nhà cung cấp", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var import = new ImportDTO()
            {
                Id = Model.ImportId,
                ImportDate = Model.ImportDate,
                ImportNumber = Model.ImportNumber,
                ImportReason = Model.ImportReason,
                Notes = Model.Notes,
                CurrencyId = Model.UsedCurrencyId,
                ExchangeRate = Model.ExchangeRate,
                SupplierId = Model.SupplierId,
                DocumentNumber = Model.ImportForDocumentNumber
            };


            try
            {
                //IEnumerable<ImportDetailDTO> allItems;
                //if (!startingInAddNewMode)
                //{
                //    allItems = _ieBC.GetImportList(Model.ImportNumber, Model.MerchandiseId)
                //    .Where(e => e.UnitPriceAfterTax == Model.UnitPriceAfterTax)
                //    .ToList();
                //}
                //else
                //{
                //    allItems = _ieBC.GetImportList(Model.ImportNumber);
                //}
                _ieBC.SaveImport(import,
                    _importDetails.ToList(),
                    Model.CurrentEditMode == Views.Export.NewEditImport.EditMode.EditExisting);

                LoadMerchandiseLookupData();
                if (OnImportSaved != null)
                    OnImportSaved(true);
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("Đã xảy ra lỗi khi nhập kho. Các thao tác đã bị hủy, bạn hãy thử lại sau" + ex.Message, "Lỗi khi nhập kho", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (OnImportSaved != null)
                    OnImportSaved(false);
            }
        }

        public void LoadExistingImportList(string importNumber)
        {
            var list = _ieBC.GetImportList(importNumber)
                .ToList();
            foreach (var item in list)
            {
                Model.ImportDetailList.Add(item);
            }


            var import = _ieBC.GetImportByNumber(importNumber);
            Model.SupplierId = import.SupplierId;
            Model.ImportReason = import.ImportReason;
            Model.Notes = import.Notes;
            Model.UsedCurrencyId = import.CurrencyId;
            Model.ExchangeRate = import.ExchangeRate;
            Model.ImportForDocumentNumber = import.DocumentNumber;
        }

        public void LoadSupplierList()
        {
            var list = _supBC.GetSupplierList().ToList();
            Model.SupplierList = list;
        }
    }
}
